//
//  FCCChatViewController.swift
//  chatUIDemo
//
//  Created by admin on 2025/7/10.
//

import UIKit
import AVFoundation
import SnapKit

class FCCChatViewController: UIViewController {
    
    // MARK: - UI组件
    private let qfcTableView = UITableView()
    private let qfcInputContainerView = UIView()
    private let qfcTextView = UITextView()
    private let qfcSendButton = UIButton()
    private let qfcImageButton = UIButton()
    private let qfcAudioButton = UIButton()
    
    // MARK: - 数据
    private let qfcMessageManager: FCCMessageManager
    private let qfcCurrentUserId = "current_user"
    
    // MARK: - 约束
    private var qfcInputContainerBottomInset: CGFloat = 0
    
    // MARK: - 初始化
    init(qfcConversationId: String? = nil) {
        qfcMessageManager = FCCMessageManager(qfcCurrentUserId: qfcCurrentUserId)
        super.init(nibName: nil, bundle: nil)
        
        // 如果提供了会话ID，可以在这里加载特定会话的消息
        // 目前仅作为示例，实际实现需要根据会话ID加载对应的消息
    }
    
    required init?(coder: NSCoder) {
        qfcMessageManager = FCCMessageManager(qfcCurrentUserId: qfcCurrentUserId)
        super.init(coder: coder)
    }
    
    // MARK: - 生命周期
    override func viewDidLoad() {
        super.viewDidLoad()
        qfcSetupUI()
        qfcSetupKeyboardObservers()
        qfcSetupMessageManager()
        qfcLoadSampleMessages()
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    // MARK: - UI设置
    private func qfcSetupUI() {
        view.backgroundColor = .systemBackground
        title = "Chat"
        
        qfcSetupTableView()
        qfcSetupInputContainer()
        qfcSetupConstraints()
        qfcSetupGestures()
    }
    
    private func qfcSetupTableView() {
        qfcTableView.delegate = self
        qfcTableView.dataSource = self
        qfcTableView.separatorStyle = .none
        qfcTableView.backgroundColor = .systemBackground
        qfcTableView.keyboardDismissMode = .onDrag
        
        // 注册Cell
        qfcTableView.register(FCCTextMessageCell.self, forCellReuseIdentifier: "FCCTextMessageCell")
        qfcTableView.register(FCCImageMessageCell.self, forCellReuseIdentifier: "FCCImageMessageCell")
        qfcTableView.register(FCCAudioMessageCell.self, forCellReuseIdentifier: "FCCAudioMessageCell")
        
        view.addSubview(qfcTableView)
    }
    
    private func qfcSetupInputContainer() {
        qfcInputContainerView.backgroundColor = .systemBackground
        qfcInputContainerView.layer.borderWidth = 0.5
        qfcInputContainerView.layer.borderColor = UIColor.separator.cgColor
        view.addSubview(qfcInputContainerView)
        
        // 文本输入框
        qfcTextView.font = UIFont.systemFont(ofSize: 16)
        qfcTextView.layer.cornerRadius = 18
        qfcTextView.layer.borderWidth = 1
        qfcTextView.layer.borderColor = UIColor.separator.cgColor
        qfcTextView.textContainerInset = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8)
        qfcTextView.delegate = self
        qfcTextView.backgroundColor = UIColor.white
        qfcInputContainerView.addSubview(qfcTextView)
        
        // Send button
        qfcSendButton.setTitle("Send", for: .normal)
        qfcSendButton.setTitleColor(.white, for: .normal)
        qfcSendButton.backgroundColor = .systemBlue
        qfcSendButton.layer.cornerRadius = 18
        qfcSendButton.addTarget(self, action: #selector(qfcSendButtonTapped), for: .touchUpInside)
        qfcInputContainerView.addSubview(qfcSendButton)
        
        // 图片按钮
        qfcImageButton.setImage(UIImage(systemName: "photo"), for: .normal)
        qfcImageButton.tintColor = .systemBlue
        qfcImageButton.addTarget(self, action: #selector(qfcImageButtonTapped), for: .touchUpInside)
        qfcInputContainerView.addSubview(qfcImageButton)
        
        // 语音按钮
        qfcAudioButton.setImage(UIImage(systemName: "mic"), for: .normal)
        qfcAudioButton.tintColor = .systemBlue
        qfcAudioButton.addTarget(self, action: #selector(qfcAudioButtonTapped), for: .touchUpInside)
        qfcInputContainerView.addSubview(qfcAudioButton)
    }
    
    private func qfcSetupConstraints() {
        
        // 输入容器约束
        qfcInputContainerView.snp.makeConstraints { make in
            make.leading.trailing.equalToSuperview()
            make.bottom.equalTo(view.safeAreaLayoutGuide).offset(-qfcInputContainerBottomInset)
            make.height.greaterThanOrEqualTo(60)
        }
        
        // TableView约束
        qfcTableView.snp.makeConstraints { make in
            make.top.equalTo(view.safeAreaLayoutGuide)
            make.leading.trailing.equalToSuperview()
            make.bottom.equalTo(qfcInputContainerView.snp.top)
        }
        

        
        // 图片按钮约束
        qfcImageButton.snp.makeConstraints { make in
            make.leading.equalTo(qfcInputContainerView).offset(12)
            make.bottom.equalTo(qfcInputContainerView).offset(-12)
            make.width.height.equalTo(36)
        }
        
        // 语音按钮约束
        qfcAudioButton.snp.makeConstraints { make in
            make.leading.equalTo(qfcImageButton.snp.trailing).offset(8)
            make.bottom.equalTo(qfcInputContainerView).offset(-12)
            make.width.height.equalTo(36)
        }
        
        // 发送按钮约束
        qfcSendButton.snp.makeConstraints { make in
            make.trailing.equalTo(qfcInputContainerView).offset(-12)
            make.bottom.equalTo(qfcInputContainerView).offset(-12)
            make.width.equalTo(60)
            make.height.equalTo(36)
        }
        
        // 文本输入框约束
        qfcTextView.snp.makeConstraints { make in
            make.leading.equalTo(qfcAudioButton.snp.trailing).offset(8)
            make.trailing.equalTo(qfcSendButton.snp.leading).offset(-8)
            make.top.equalTo(qfcInputContainerView).offset(12)
            make.bottom.equalTo(qfcInputContainerView).offset(-12)
            make.height.equalTo(36)
        }
    }
    
    private func qfcSetupGestures() {
        let qfcTapGesture = UITapGestureRecognizer(target: self, action: #selector(qfcDismissKeyboard))
        qfcTapGesture.cancelsTouchesInView = false  // 允许点击事件继续传递
        qfcTableView.addGestureRecognizer(qfcTapGesture)
    }
    
    private func qfcSetupMessageManager() {
        qfcMessageManager.qfcDelegate = self
    }
    
    // MARK: - 键盘处理
    private func qfcSetupKeyboardObservers() {
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(qfcKeyboardWillShow),
            name: UIResponder.keyboardWillShowNotification,
            object: nil
        )
        
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(qfcKeyboardWillHide),
            name: UIResponder.keyboardWillHideNotification,
            object: nil
        )
    }
    
    @objc private func qfcKeyboardWillShow(_ qfcNotification: Notification) {
        guard let qfcKeyboardFrame = qfcNotification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect,
              let qfcDuration = qfcNotification.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double else {
            return
        }
        
        qfcInputContainerBottomInset = qfcKeyboardFrame.height - view.safeAreaInsets.bottom
        
        qfcInputContainerView.snp.updateConstraints { make in
            make.bottom.equalTo(view.safeAreaLayoutGuide).offset(-qfcInputContainerBottomInset)
        }
        
        UIView.animate(withDuration: qfcDuration) {
            self.view.layoutIfNeeded()
        }
        
        qfcScrollToBottom()
    }
    
    @objc private func qfcKeyboardWillHide(_ qfcNotification: Notification) {
        guard let qfcDuration = qfcNotification.userInfo?[UIResponder.keyboardAnimationDurationUserInfoKey] as? Double else {
            return
        }
        
        qfcInputContainerBottomInset = 0
        
        qfcInputContainerView.snp.updateConstraints { make in
            make.bottom.equalTo(view.safeAreaLayoutGuide).offset(-qfcInputContainerBottomInset)
        }
        
        UIView.animate(withDuration: qfcDuration) {
            self.view.layoutIfNeeded()
        }
    }
    
    @objc private func qfcDismissKeyboard() {
        view.endEditing(true)
    }
    
    // MARK: - 按钮事件
    @objc private func qfcSendButtonTapped() {
        guard !qfcTextView.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
            return
        }
        
        let qfcContent = qfcTextView.text.trimmingCharacters(in: .whitespacesAndNewlines)
        qfcSendTextMessage(qfcContent)
        qfcTextView.text = ""
        // 更新文本视图高度约束
        qfcTextView.snp.updateConstraints { make in
            make.height.equalTo(36)
        }
        
        qfcTextView.snp.updateConstraints { make in
            make.height.equalTo(36)
        }
        
        qfcInputContainerView.snp.updateConstraints { make in
            make.height.greaterThanOrEqualTo(60)
        }
    }
    
    @objc private func qfcImageButtonTapped() {
        
        let qfcImagePicker = UIImagePickerController()
        qfcImagePicker.delegate = self
        qfcImagePicker.sourceType = .photoLibrary
        present(qfcImagePicker, animated: true)
    }
    
    @objc private func qfcAudioButtonTapped() {
        // 模拟发送语音消息
        qfcSendAudioMessage(duration: Int.random(in: 1...60))
    }
    
    // MARK: - 发送消息
    private func qfcSendTextMessage(_ qfcContent: String) {
        qfcMessageManager.qfcSendTextMessage(qfcContent)
    }
    
    private func qfcSendImageMessage(_ qfcImage: UIImage) {
        qfcMessageManager.qfcSendImageMessage(qfcImage)
    }
    
    private func qfcSendAudioMessage(duration: Int) {
        qfcMessageManager.qfcSendAudioMessage(qfcDuration: duration)
    }
    
    private func qfcScrollToBottom() {
        let qfcMessages = qfcMessageManager.qfcGetAllMessages()
        guard !qfcMessages.isEmpty else { return }
        
        let qfcIndexPath = IndexPath(row: qfcMessages.count - 1, section: 0)
        qfcTableView.scrollToRow(at: qfcIndexPath, at: .bottom, animated: true)
    }
    
    // MARK: - 示例数据
    private func qfcLoadSampleMessages() {
        qfcMessageManager.qfcLoadHistoryMessages()
        qfcTableView.reloadData()
        
        // 模拟接收新消息
        DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) {
            self.qfcMessageManager.qfcSimulateReceiveMessage()
        }
    }
}

// MARK: - UITableViewDataSource
extension FCCChatViewController: UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return qfcMessageManager.qfcGetAllMessages().count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let qfcMessages = qfcMessageManager.qfcGetAllMessages()
        let qfcMessage = qfcMessages[indexPath.row]
        
        switch qfcMessage.qfcType {
        case .qfcText:
            let qfcCell = tableView.dequeueReusableCell(withIdentifier: "FCCTextMessageCell", for: indexPath) as! FCCTextMessageCell
            qfcCell.qfcConfigureTextMessage(qfcMessage as! FCCTextMessage)
            return qfcCell
            
        case .qfcImage:
            let qfcCell = tableView.dequeueReusableCell(withIdentifier: "FCCImageMessageCell", for: indexPath) as! FCCImageMessageCell
            qfcCell.qfcConfigureImageMessage(qfcMessage as! FCCImageMessage)
            return qfcCell
            
        case .qfcAudio:
            let qfcCell = tableView.dequeueReusableCell(withIdentifier: "FCCAudioMessageCell", for: indexPath) as! FCCAudioMessageCell
            qfcCell.qfcConfigureAudioMessage(qfcMessage as! FCCAudioMessage)
            return qfcCell
        }
    }
}

// MARK: - UITableViewDelegate
extension FCCChatViewController: UITableViewDelegate {
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        
        let qfcMessages = qfcMessageManager.qfcGetAllMessages()
        let qfcMessage = qfcMessages[indexPath.row]
        
        switch qfcMessage.qfcType {
        case .qfcImage:
            qfcShowImagePreview(qfcMessage as! FCCImageMessage)
        case .qfcAudio:
            qfcPlayAudioMessage(qfcMessage as! FCCAudioMessage)
        default:
            break
        }
    }
    
    private func qfcShowImagePreview(_ qfcMessage: FCCImageMessage) {
        guard let qfcImage = qfcMessage.qfcImage else { return }
        
        // 查找消息对应的单元格
        if let qfcIndex = qfcMessageManager.qfcGetAllMessages().firstIndex(where: { $0.qfcId == qfcMessage.qfcId }),
           let qfcCell = qfcTableView.cellForRow(at: IndexPath(row: qfcIndex, section: 0)) as? FCCImageMessageCell {
            
            // 获取图片视图在屏幕上的位置
            let qfcSourceFrame = qfcCell.qfcImageContentView.convert(qfcCell.qfcImageContentView.bounds, to: nil)
            
            // 确保图片视图有正确的圆角和边界
            let qfcCornerRadius = qfcCell.qfcImageContentView.layer.cornerRadius
            
            // 使用带有转场动画的初始化方法
            let qfcImagePreview = FCCImagePreviewViewController(qfcImage: qfcImage, qfcSourceView: qfcCell.qfcImageContentView, qfcSourceFrame: qfcSourceFrame)
            
            // 设置转场动画的模态呈现样式
            qfcImagePreview.modalPresentationStyle = .overFullScreen
            qfcImagePreview.modalTransitionStyle = .crossDissolve
            
            present(qfcImagePreview, animated: false) // 使用false，因为我们使用自定义动画
        } else {
            // 如果找不到单元格（可能已滚动出屏幕），则使用普通方式展示
            let qfcImagePreview = FCCImagePreviewViewController(qfcImage: qfcImage)
            qfcImagePreview.modalPresentationStyle = .fullScreen
            present(qfcImagePreview, animated: true)
        }
    }
    
    private func qfcPlayAudioMessage(_ qfcMessage: FCCAudioMessage) {
        qfcMessage.qfcIsPlaying.toggle()
        
        let qfcMessages = qfcMessageManager.qfcGetAllMessages()
        if let qfcIndex = qfcMessages.firstIndex(where: { $0.qfcId == qfcMessage.qfcId }) {
            let qfcIndexPath = IndexPath(row: qfcIndex, section: 0)
            qfcTableView.reloadRows(at: [qfcIndexPath], with: .none)
        }
        
        // 模拟播放完成
        if qfcMessage.qfcIsPlaying {
            DispatchQueue.main.asyncAfter(deadline: .now() + Double(qfcMessage.qfcDuration)) {
                qfcMessage.qfcIsPlaying = false
                let qfcMessages = self.qfcMessageManager.qfcGetAllMessages()
                if let qfcIndex = qfcMessages.firstIndex(where: { $0.qfcId == qfcMessage.qfcId }) {
                    let qfcIndexPath = IndexPath(row: qfcIndex, section: 0)
                    self.qfcTableView.reloadRows(at: [qfcIndexPath], with: .none)
                }
            }
        }
    }
    
    // MARK: - 长按菜单
    func tableView(_ tableView: UITableView, contextMenuConfigurationForRowAt indexPath: IndexPath, point: CGPoint) -> UIContextMenuConfiguration? {
        let qfcMessages = qfcMessageManager.qfcGetAllMessages()
        let qfcMessage = qfcMessages[indexPath.row]
        
        return UIContextMenuConfiguration(identifier: nil, previewProvider: nil) { _ in
            return self.qfcCreateContextMenu(for: qfcMessage)
        }
    }
    
    private func qfcCreateContextMenu(for qfcMessage: FCCMessage) -> UIMenu {
        var qfcActions: [UIAction] = []
        
        // Copy action
        let qfcCopyAction = UIAction(title: "Copy", image: UIImage(systemName: "doc.on.doc")) { _ in
            self.qfcMessageManager.qfcCopyMessage(qfcMessage.qfcId)
        }
        qfcActions.append(qfcCopyAction)
        
        // Forward action
        let qfcForwardAction = UIAction(title: "Forward", image: UIImage(systemName: "arrowshape.turn.up.right")) { _ in
            self.qfcMessageManager.qfcForwardMessage(qfcMessage.qfcId)
        }
        qfcActions.append(qfcForwardAction)
        
        // Delete action (only for outgoing messages)
        if qfcMessage.qfcIsOutgoing {
            let qfcDeleteAction = UIAction(title: "Delete", image: UIImage(systemName: "trash"), attributes: .destructive) { _ in
                self.qfcDeleteMessage(qfcMessage.qfcId)
            }
            qfcActions.append(qfcDeleteAction)
            
            // Resend action (only for failed messages)
            if qfcMessage.qfcStatus == .qfcFailed {
                let qfcResendAction = UIAction(title: "Resend", image: UIImage(systemName: "arrow.clockwise")) { _ in
                    self.qfcMessageManager.qfcResendMessage(qfcMessage.qfcId)
                }
                qfcActions.append(qfcResendAction)
            }
        }
        
        return UIMenu(title: "", children: qfcActions)
    }
    
    private func qfcDeleteMessage(_ qfcMessageId: String) {
        let qfcMessages = qfcMessageManager.qfcGetAllMessages()
        guard let qfcIndex = qfcMessages.firstIndex(where: { $0.qfcId == qfcMessageId }) else {
            return
        }
        
        qfcMessageManager.qfcDeleteMessage(qfcMessageId)
        let qfcIndexPath = IndexPath(row: qfcIndex, section: 0)
        qfcTableView.deleteRows(at: [qfcIndexPath], with: .fade)
    }
}

// MARK: - UITextViewDelegate
extension FCCChatViewController: UITextViewDelegate {
    func textViewDidChange(_ textView: UITextView) {
        // 调整输入容器高度以适应文本输入
        let fixedWidth = textView.frame.width
        let newSize = textView.sizeThatFits(CGSize(width: fixedWidth, height: CGFloat.greatestFiniteMagnitude))
        
        // 计算文本视图的新高度（最小36）
        let textViewHeight = min(max(36, newSize.height), 70)
        
        
        // 更新文本视图高度约束
        textView.snp.updateConstraints { make in
            make.height.equalTo(textViewHeight)
        }
        
        // 计算输入容器的新高度（文本视图高度 + 上下边距）
        let containerHeight = textViewHeight + 24 // 上下各12的边距
        
        // 更新输入容器高度约束
        qfcInputContainerView.snp.updateConstraints { make in
            make.height.greaterThanOrEqualTo(max(60, containerHeight))
        }
        
        // 动画更新布局
        UIView.animate(withDuration: 0.1) {
            self.view.layoutIfNeeded()
        }
        
        // 滚动到底部
        if newSize.height > 100 {
            let bottomOffset = CGPoint(x: 0, y: textView.contentSize.height - textView.bounds.height)
            if bottomOffset.y > 0 {
                textView.setContentOffset(bottomOffset, animated: true)
            }
        }
    }
}

// MARK: - UIImagePickerControllerDelegate
extension FCCChatViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        picker.dismiss(animated: true)
        
        if let qfcSelectedImage = info[.originalImage] as? UIImage {
            qfcSendImageMessage(qfcSelectedImage)
        }
    }
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        picker.dismiss(animated: true)
    }
}

// MARK: - FCCMessageManagerDelegate
extension FCCChatViewController: FCCMessageManagerDelegate {
    func qfcMessageManager(_ qfcManager: FCCMessageManager, didReceiveMessage qfcMessage: FCCMessage) {
        let qfcMessages = qfcManager.qfcGetAllMessages()
        let qfcIndexPath = IndexPath(row: qfcMessages.count - 1, section: 0)
        qfcTableView.insertRows(at: [qfcIndexPath], with: .bottom)
        qfcScrollToBottom()
    }
    
    func qfcMessageManager(_ qfcManager: FCCMessageManager, didUpdateMessage qfcMessage: FCCMessage) {
        let qfcMessages = qfcManager.qfcGetAllMessages()
        guard let qfcIndex = qfcMessages.firstIndex(where: { $0.qfcId == qfcMessage.qfcId }) else {
            return
        }
        
        let qfcIndexPath = IndexPath(row: qfcIndex, section: 0)
        qfcTableView.reloadRows(at: [qfcIndexPath], with: .none)
    }
    
    func qfcMessageManager(_ qfcManager: FCCMessageManager, didFailToSendMessage qfcMessage: FCCMessage, error: Error) {
        // Display send failure alert
        let qfcAlert = UIAlertController(title: "Send Failed", message: error.localizedDescription, preferredStyle: .alert)
        qfcAlert.addAction(UIAlertAction(title: "OK", style: .default))
        qfcAlert.addAction(UIAlertAction(title: "Retry", style: .default) { _ in
            qfcManager.qfcResendMessage(qfcMessage.qfcId)
        })
        present(qfcAlert, animated: true)
    }
}
